package com.blueskykong.tm.common.netty.serizlize.dubbo;

import com.blueskykong.tm.common.netty.MessageCodecService;
import com.blueskykong.tm.common.netty.serizlize.hessian.HessianCodecServiceImpl;
import com.blueskykong.tm.common.netty.serizlize.kryo.KryoCodecServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author: Jason Chen
 */
public class DubboProtocolEncoder extends MessageToByteEncoder {

    private static final short DUBBO_MAGIC = (short) 0xdabb;

    private MessageCodecService util;

    public DubboProtocolEncoder(MessageCodecService messageCodecService) {
        this.util = messageCodecService;
    }

    @Override
    protected void encode(ChannelHandlerContext cxt, Object msg, ByteBuf out) throws Exception {
        out.writeShort(DUBBO_MAGIC);//增加dubbo 头魔数
        if (!setFlagAndSerialization(out)) {
            cxt.close();
        }
        out.writerIndex(out.writerIndex() + 9);//移动dubbo协议指针头
        util.encode(out, msg);//序列化对象
    }

    private boolean setFlagAndSerialization(ByteBuf out) {
        if (util instanceof HessianCodecServiceImpl) {
            out.writeByte(2);
            return true;
        }
        if (util instanceof KryoCodecServiceImpl) {
            out.writeByte(8);
            return true;
        }
        return false;
    }
}
